import config from "../../config"
import position from "../service/position"

export default abstract class canvasAbstract {
  // 数量
  public models:IModel[] = []
  abstract render(): void
  abstract num(): number
  abstract model(): ModelConstructor | BulletModelConstructor

  protected constructor(
      // 画布名称
      protected name: string,
      protected app = document.querySelector<HTMLElement>('#app')!,
      protected el = document.createElement('canvas'),
      public ctx = el.getContext('2d')!
  ) {
    this.createCanvas()
  }

  // 创建画布
  protected createCanvas() {
    this.el.width = config.canvas.width
    this.el.height = config.canvas.height
    // 为画布添加name属性
    this.el.setAttribute('name', this.name)
    // 将画布添加到页面中
    this.app.insertAdjacentElement('afterbegin', this.el)
  }

  // 绘制模型
  protected createModels() {
    position.getCollection(this.num()).forEach(position => {
      const model = this.model() as ModelConstructor
      const instance = new model(position)
      this.models.push(instance)
    })
  }

  // 渲染模型
  public renderModels() {
    this.ctx.clearRect(0, 0, config.canvas.width, config.canvas.height)
    this.models.forEach(model => model.render())
  }

  // 移除模型
  public removeModel(model: IModel) {
    this.models = this.models.filter(mo => mo !== model)
  }
}
